from django.shortcuts import render

# 自动生成路由，不重写list方法
from rest_framework.viewsets import GenericViewSet
from rest_framework.mixins import ListModelMixin, RetrieveModelMixin
from .models import CourseCategory, Course, CourseChapter
from .serializer import CourseCategorySerializer, CourseSerializer, CourseChapterSerializer
from .page import CommonPageNumberPagination
from rest_framework.filters import OrderingFilter, SearchFilter
from django_filters.rest_framework import DjangoFilterBackend


class CourseCategoryViewSet(GenericViewSet, ListModelMixin):
    queryset = CourseCategory.objects.all().filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseCategorySerializer


# 查询所有和查询单个接口
class CourseViewSet(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = Course.objects.all().filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseSerializer
    # 带分页
    pagination_class = CommonPageNumberPagination
    # 排序功能:学生人数，价格，id
    filter_backends = [OrderingFilter, DjangoFilterBackend]
    ordering_fields = ['id', 'students', 'price']

    # 支持过滤，按课程分类过滤：需要借助于django-filter
    # http://127.0.0.1:8080/api/v1/course/actual/?course_category=2
    filter_fields = ['course_category']


class CourseChapterViewSet(GenericViewSet, ListModelMixin):
    queryset = CourseChapter.objects.all().filter(is_show=True, is_delete=False).order_by('orders')
    serializer_class = CourseChapterSerializer
    # 根据课程过滤功能
    filter_backends = [DjangoFilterBackend]
    filter_fields = ['course']


# 搜索接口
class CourseSearchViewSet(GenericViewSet, ListModelMixin, RetrieveModelMixin):
    queryset = Course.objects.all().filter(is_delete=False, is_show=True).order_by('orders')
    serializer_class = CourseSerializer
    # 带分页
    pagination_class = CommonPageNumberPagination

    # 搜索，按名字模糊搜索，或者按介绍搜索
    filter_backends = [SearchFilter]
    search_fields = ['name', 'brief']

    # 如果想全文检索----》只要在brief中有关键字，就能搜索出来---》类似于百度
    # 如果使用mysql的like搜索，数据量越大，速度越慢
    # 后期咱们需要使用专业的搜索引擎---》Elasticsearch：分布式全文检索引擎


    # 如果这个搜索接口，返回多种课程，重写list
    # def list(self, request, *args, **kwargs):
    #     # 只返回了实战课，后期有免费，轻课，一次性返回
    #
    #     response=super().list(request, *args, **kwargs)
    #     # response.data
    #
    #     # [{},{},{}]--->{'actual_course':[],'free_course':[],'lite_course':[]}
    #     res={'actual_course':response.data,'free_course':[],'lite_course':[]}
    #     return Response(data=res)